package com.lagou.utils;

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class ImageUploadUtils {

    public  HashMap<String, String> ImageUpload(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.判断接收到的上传文件是否为空，isEmpty判断字符长度
        if (file.isEmpty()) {
            //为空抛出异常
            throw new RuntimeException();
        }
        //2.获取项目部署路径
        // 获取到的路径为： D:\IT\apache-tomcat-8.5.55\webapps\ssm_web\
        String realPath = request.getServletContext().getRealPath("/");
        // 获取到：D:\IT\apache-tomcat-8.5.55\webapps\
        String webappsPath = realPath.substring(0, realPath.indexOf("ssm_web"));

        //3.获取原文件名
        //lagou.jpg
        String originalFilename = file.getOriginalFilename();

        //4.生成新文件名
        String FileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //5.文件上传

        String uploadPath = webappsPath + "upload\\";
        //
        File filePath = new File(uploadPath, FileName);

        //如果目录不存在就创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录：" + filePath);
        }

        //图片就进行了真正的上传
        file.transferTo(filePath);

        //6.将文件名和放假路径返回，进行响应
        HashMap<String, String> map = new HashMap<>();
        map.put("fileName", FileName);
        map.put("filePath", "http://localhost:8080/upload/" + FileName);
        return map;
    }

}
